<?php
class Pageley_Basic_Command_Query extends Pageley_Controller_Command_TransactionalRead {

    private $propertyNames;
    private $operators;
    private $values;
    private $inversions;
	private $typeName;

	public function setPropertyNames($propertyNames) {
		$this->propertyNames = $propertyNames;
	}

	public function setOperators($operators) {
		$this->operators = $operators;
	}

	public function setValues($values) {
		$this->values = $values;
	}

	public function setInversions($inversions) {
		$this->inversions = $inversions;
	}

	public function setTypeName($typeName) {
		$this->typeName = $typeName;
	}

	protected function executeInternal() {
		$unitOfWork = $this->getUnitOfWork();
        $factory = Pageley_Config::getInstance();
		$type = $factory->valueOf("type." . $this->typeName);
		$queryConditions = $this->createConditions($type);
        $query = new Pageley_Query_Basic(
			$type,
			$queryConditions !== null ?
			new Pageley_Query_Condition_AndGroup(
                $queryConditions
            ) : null);
        $model = new Pageley_Util_ArrayMap();
		$model->put("entities", $unitOfWork->query($query));
		return new Pageley_Controller_ModelAndView($model);
	}

    private function createConditions($type) {
        $queryConditions = null;
    	if($this->propertyNames != null) {
	        $queryConditions = new Pageley_Util_ArrayMap();
	        $factory = Pageley_Query_Condition_Factory::getInstance();
        	foreach($this->propertyNames as $index => $propertyName) {
        		// TODO: add type to resolve values.
	            $queryConditions->add($factory->createCondition(
	                $type, 
	                $propertyName, 
	                $this->operators != null ? $this->operators->get($index) : "=",
	                $this->values != null ? $this->values->get($index) : null,
	                $this->inversions != null ? $this->inversions->get($index) : false));
	        }
        }
        return $queryConditions;
    }
}